package org.example.demo.service.userService.impl;

import org.example.demo.service.userService.FavoriteService;
import org.example.demo.service.userService.ProductService;
import org.example.mbg.mapper.FavoriteMapper;
import org.example.mbg.mapper.ProductMapper;
import org.example.mbg.model.Favorite;
import org.example.mbg.model.FavoriteExample;
import org.example.mbg.model.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class FavoriteServiceImpl implements FavoriteService {

    @Autowired
    private FavoriteMapper favoriteMapper;

    @Autowired
    private ProductService productService;

    @Override
    public int addFavorite(Long user_id, Long product_id) {
        //操作数
        int operation_count = 0;
        // 判断商品是否存在于该用户的收藏夹
        System.out.println("add fav");

        FavoriteExample favoriteExample = new FavoriteExample();
        favoriteExample.createCriteria().andUserIdEqualTo(user_id).andShopIdEqualTo(product_id);
        if (favoriteMapper.selectByExample(favoriteExample).isEmpty()) {

            Favorite newFavorite = new Favorite();

            newFavorite.setShopId(product_id);
            newFavorite.setUserId(user_id);
            newFavorite.setCollectTime(new Date());

            operation_count = favoriteMapper.insertSelective(newFavorite);
            productService.addFavourite(product_id);

        }

        // 商品收藏数变化

        return operation_count;
    }

    @Override
    public int cancelFavorite(Long user_id, Long product_id) {
        System.out.println("cancel fav");
        int operation_count = 0;
        FavoriteExample favoriteExample = new FavoriteExample();
        favoriteExample.createCriteria().andUserIdEqualTo(user_id).andShopIdEqualTo(product_id);

        operation_count = favoriteMapper.deleteByExample(favoriteExample);

        // 商品收藏数变化
        if (operation_count > 0)
            productService.cancelFavourite(product_id);
        return operation_count;
    }

}
